﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media.Imaging;

namespace LFMTest.WinRT.Converters
{
    public class TrackThumbGenerator : IValueConverter
    {
        public object Convert(object value, string typeName, object parameter, string language)
        {
            var llama = String.Empty;

            try
            {
                MusicStorageFile source = (MusicStorageFile)value;

                //var thumb = await source.File.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.MusicView);
                source.File.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.MusicView).Start();
                while (source.File.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.MusicView).Status != Windows.Foundation.AsyncStatus.Completed) Thread.Sleep(10);

                var thumb = source.File.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.MusicView).GetResults();
                BitmapImage bmp = new BitmapImage();
                bmp.CreateOptions = BitmapCreateOptions.BackgroundCreation;
                bmp.DecodePixelHeight = 150;
                bmp.DecodePixelWidth = 150;

                InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
                RandomAccessStream.Copy(thumb.GetInputStreamAt(0), ras.GetOutputStreamAt(0));
                bmp.SetSource((IRandomAccessStream)ras);

                return bmp;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public object ConvertBack(object value, string typeName, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}
